package com.sixuan.rabbitmqconsumer.workmode.topic;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * RabbitMq工作模式：Topics（通配符模式）
 * 1.生命一个交换机，并指定该交换机是TOPIC模式（即topics模式）。
 * 2.通配符有两种形式:通配符之间用<.>号隔开
 * (1)<info.#.email>:#可以识别多个词
 * (2)<info.*.email>:*只能识别一个词
 * eg：info.sms.example.email能被（1）识别，但是不能被（2）识别
 * Topics模式比Routing模式更强大。
 * <p>
 * Created by Gynco on 2020/7/8 21:37
 *
 * @author Gynco
 */
public class SmsConsumer {
    private static final String rabbitMqHost = "47.97.195.191";
    private static final int rabbitMqPort = 5672;
    private static final String username = "guest";
    private static final String password = "guest";

    private static final String SMS_QUEUE_INFORMATION = "sms_queue_information";
    private static final String EXCHANGE_TOPIC = "exchange_topic";
    private static final String SMS_TOPIC_INFORMATION = "info.#.sms.#";

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(rabbitMqHost);
        connectionFactory.setPort(rabbitMqPort);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_TOPIC, BuiltinExchangeType.TOPIC);
        //声明队列
        channel.queueDeclare(SMS_QUEUE_INFORMATION, true, false, false, null);
        //将队列绑定到交换机上
        channel.queueBind(SMS_QUEUE_INFORMATION, EXCHANGE_TOPIC, SMS_TOPIC_INFORMATION);

        //接收到消息后的执行方法
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //交换机
                String exchange = envelope.getExchange();
                long deliveryTag = envelope.getDeliveryTag();
                String message = new String(body, "utf-8");
                System.out.println("Received from provider : " + message);
            }
        };
        //监听消息basicConsume
        channel.basicConsume(SMS_QUEUE_INFORMATION, true, defaultConsumer);
    }
}
